﻿using System.Reflection;

using MediatR;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Tszy.Unlimited.Base.Infrastructure.Caching;
using Tszy.Unlimited.Base.Infrastructure.Logging;
using Tszy.Unlimited.Base.Infrastructure.Stores;

namespace Tszy.Unlimited.Base;

/// <summary>
/// 启动器。
/// </summary>
public static class Startup
{
    /// <summary>
    /// 注册基础功能模块。
    /// </summary>
    /// <param name="services">IoC 服务。</param>
    /// <param name="configuration">配置信息。</param>
    /// <returns></returns>
    public static IServiceCollection RegisterTszyComponent(this IServiceCollection services, IConfiguration? configuration = null)
    {
        if (configuration != null)
        {
            services.RegisterLogger(configuration);
        }

        services.RegisterCache(CacheManager.Current);
        services.RegisterScopeStore();

        var assemblies = GetAssemblies();

        services.AddMediatR(assemblies);
        services.AddAutoMapper(assemblies);

        return services;
    }

    private static Assembly[] GetAssemblies()
    {
        var ignore = new string[]
        {
            "Microsoft",
            "System",
            "AutoMapper",
            "Newtonsoft",
            "Serilog",
            "SixLabors",
            "RestSharp",
            "Newtonsoft",
            "MediatR",
            "Dapper",
            "CSRedis",
            "CommonMark",
            "BouncyCastle",
            "netstandard"
        };

        return AppDomain.CurrentDomain.GetAssemblies().Where(item => !ignore.Any(i => item.FullName?.StartsWith(i) ?? false)).ToArray();
    }
}